package com.ruoyi.training.service.impl;

import java.util.ArrayList;
import java.util.List;

import com.alibaba.nacos.common.utils.CollectionUtils;
import com.ruoyi.common.core.utils.DateUtils;
import com.ruoyi.common.security.utils.SecurityUtils;
import com.ruoyi.training.domain.*;
import com.ruoyi.training.dto.ActivityCheckinDTO;
import com.ruoyi.training.dto.CheckinDetailsQuery;
import com.ruoyi.training.dto.ClassCheckinDto;
import com.ruoyi.training.dto.StudentCheckinDTO;
import com.ruoyi.training.mapper.*;
import com.ruoyi.training.util.xuehua.SnowflakeIdUtils;
import com.ruoyi.training.vo.CheckinDetailsResult;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.ruoyi.training.service.IClassCheckinService;

/**
 * 班级签到活动（单节课程的签到配置）Service业务层处理
 *
 * @author WorrilessGo
 * @date 2025-09-24
 */
@Service
public class ClassCheckinServiceImpl implements IClassCheckinService {
    private static final SnowflakeIdUtils snowflake = new SnowflakeIdUtils(5, 8);

    @Autowired
    private ClassCheckinMapper classCheckinMapper;

    @Autowired
    private TrainingScheduleMapper trainingScheduleMapper;

    @Autowired
    private ClassStudentMapper classStudentMapper;

    @Autowired
    private StudentsMapper studentsMapper;

    @Autowired
    private RegistrationMapper registrationMapper;

    @Autowired
    private ProjectsMapper projectsMapper;

    @Autowired
    private CheckinRecordMapper checkinRecordMapper;

    /**
     * 查询班级签到活动（单节课程的签到配置）
     *
     * @param classCheckinId 班级签到活动（单节课程的签到配置）主键
     * @return 班级签到活动（单节课程的签到配置）
     */
    @Override
    public ClassCheckin selectClassCheckinByClassCheckinId(String classCheckinId) {
        return classCheckinMapper.selectClassCheckinByClassCheckinId(classCheckinId);
    }

    /**
     * 查询班级签到活动（单节课程的签到配置）列表
     *
     * @param classCheckin 班级签到活动（单节课程的签到配置）
     * @return 班级签到活动（单节课程的签到配置）
     */
    @Override
    public List<ClassCheckin> selectClassCheckinList(ClassCheckin classCheckin) {
        return classCheckinMapper.selectClassCheckinList(classCheckin);
    }

    /**
     * 新增班级签到活动（单节课程的签到配置）
     *
     * @param classCheckin 班级签到活动（单节课程的签到配置）
     * @return 结果
     */
    @Override
    public int insertClassCheckin(ClassCheckin classCheckin) {
        classCheckin.setCreateTime(DateUtils.getNowDate());
        classCheckin.setClassCheckinId(String.valueOf(snowflake.nextId()));
        classCheckin.setCreateBy(SecurityUtils.getLoginUser().getSysUser().getNickName());
        return classCheckinMapper.insertClassCheckin(classCheckin);
    }

    /**
     * 修改班级签到活动（单节课程的签到配置）
     *
     * @param classCheckin 班级签到活动（单节课程的签到配置）
     * @return 结果
     */
    @Override
    public int updateClassCheckin(ClassCheckin classCheckin) {
        classCheckin.setUpdateTime(DateUtils.getNowDate());
        classCheckin.setUpdateBy(SecurityUtils.getLoginUser().getSysUser().getNickName());
        return classCheckinMapper.updateClassCheckin(classCheckin);
    }

    /**
     * 批量删除班级签到活动（单节课程的签到配置）
     *
     * @param classCheckinIds 需要删除的班级签到活动（单节课程的签到配置）主键
     * @return 结果
     */
    @Override
    public int deleteClassCheckinByClassCheckinIds(String[] classCheckinIds) {
        return classCheckinMapper.deleteClassCheckinByClassCheckinIds(classCheckinIds);
    }

    /**
     * 删除班级签到活动（单节课程的签到配置）信息
     *
     * @param classCheckinId 班级签到活动（单节课程的签到配置）主键
     * @return 结果
     */
    @Override
    public int deleteClassCheckinByClassCheckinId(String classCheckinId) {
        return classCheckinMapper.deleteClassCheckinByClassCheckinId(classCheckinId);
    }

    /**
     * 查询班级签到活动列表
     * lqx
     */
    @Override
    public List<ClassCheckinDto> selectList(ClassCheckin classCheckin) {
        //通过班级id查询出当前班级的签到
        System.out.println(classCheckin);
        List<ClassCheckin> classCheckinList = classCheckinMapper.selectClassCheckinList(classCheckin);
        List<ClassCheckinDto> classCheckinDtoList = new ArrayList<>();
        for (ClassCheckin checkin : classCheckinList) {
            ClassCheckinDto classCheckinDto = new ClassCheckinDto();
            //赋值
            BeanUtils.copyProperties(checkin,classCheckinDto);
            //处理值
            TrainingSchedule trainingSchedule = trainingScheduleMapper.selectTrainingScheduleByTrainingScheduleId(classCheckinDto.getTrainingScheduleId());
            if (trainingSchedule != null){
                classCheckinDto.setTrainingContent(trainingSchedule.getTrainingContent());
            }
            classCheckinDtoList.add(classCheckinDto);
        }
        return classCheckinDtoList;
    }

    /**
     * 查询班级签到详情
     * lqx
     */
    @Override
    public List<CheckinDetailsResult> selectCheckinDetails(CheckinDetailsQuery checkinDetailsQuery) {
        return classCheckinMapper.selectCheckinDetails(checkinDetailsQuery);
    }

    /**
     * 通过班级id查询所有签到详情
     * lqx
     */
    @Override
    public List<StudentCheckinDTO> selectAllCheckinDetailsByClassId(CheckinDetailsQuery checkinDetailsQuery) {
        String classId = checkinDetailsQuery.getTrainingClassId();
        // 1. 查询班级所有在班学员
        List<ClassStudent> classStudents = classStudentMapper.selectClassStudentsByClassId(classId);
        if (CollectionUtils.isEmpty(classStudents)) {
            return new ArrayList<>();
        }
        // 2. 查询班级所有签到活动
        List<ClassCheckin> classCheckins = classCheckinMapper.selectByTrainingClassId(classId);
        System.out.println("classCheckins = " + classCheckins);

        List<StudentCheckinDTO> resultList = new ArrayList<>();

        // 3. 处理每个学员的信息和签到状态
        for (ClassStudent classStudent : classStudents) {
            StudentCheckinDTO dto = new StudentCheckinDTO();

            // 3.1 封装学员基本信息
            Students student = studentsMapper.selectStudentsByStudentId(classStudent.getStudentId());
            if (student != null) {
                dto.setStudentId(student.getStudentId());
                dto.setStudentName(student.getStudentName());
                dto.setIdNumber(student.getIdNumber());
                dto.setPhoneNumber(student.getPhonenumber());
            }

            // 3.2 封装项目信息
            if (classStudent.getRegistrationId() != null) {
                Registration registration = registrationMapper.selectByRegistrationId(classStudent.getRegistrationId());
                if (registration != null && registration.getProjectId() != null) {
                    Projects project = projectsMapper.selectProjectsByProjectId(registration.getProjectId());
                    if (project != null) {
                        dto.setProjectId(project.getProjectId());
                        dto.setProjectName(project.getProjectName());
                    }
                }
            }
            // 3.3 封装各活动签到情况
            List<ActivityCheckinDTO> activityCheckins = new ArrayList<>();
            for (ClassCheckin checkin : classCheckins) {
                System.out.println("checkin = " + checkin);
                ActivityCheckinDTO activityDTO = new ActivityCheckinDTO();
                BeanUtils.copyProperties(checkin, activityDTO);

                // 查询该学员在当前活动的签到记录
                CheckinRecord record = checkinRecordMapper.selectByActivityAndStudent(
                        checkin.getClassCheckinId(), classStudent.getStudentId());

                // 设置签到状态（默认未签到）
                activityDTO.setCheckinStatus(Math.toIntExact(record != null ? record.getCheckinStatus() : 0));
                if (record != null) {
                    activityDTO.setCheckinRemark(record.getCheckinRemark());
                    activityDTO.setActualCheckinTime(record.getActualCheckinTime());
                }

                activityCheckins.add(activityDTO);
            }
            dto.setActivityCheckins(activityCheckins);

            resultList.add(dto);
        }


        return resultList;
    }
}
